$(document)
		.ready(
				function() {
					var contextPath = document.location.pathname; 
					var index =contextPath.substr(1).indexOf("/"); 
					contextPath = contextPath.substr(1,index); 
				var basePath="/"+contextPath;
                	var uploader;
					var totalCount = $("#totalCount").val();
					var pSize = $("#pageSize").val();
					var proId=$("#productId").val();
					
					var pageIndex = $("#pageIndex").val();
					var pageCount = $("#pageCount").val();
					initUploader();
					$("#protypeDetail").on('hidden.bs.modal', function() {
						$(this).removeData("bs.modal");
					});

					$("#optBtn").delegate(
							'#saveBtn',
							'click',
							function() {

								$("#productDetail").attr("method", "post");

								var proId = $("#proId").val();
								
								if (proId == "" || proId == null
										|| proId == "undefined") {

									$("#productDetail").attr("action",
											"save.do");
									
								} else {
									$("#productDetail").attr("action",
											"update.do");
									
								}
								$("#productDetail").submit();

							});

					$('#pagination2')
							.jqPaginator(
									{
										//totalPages : pageCount,
										totalCounts:totalCount,
										pageSize : pSize,
										visiblePages : pageCount,
										currentPage : 1,

										prev : '<li class="prev"><a href="javascript:void(0);">上一页</a></li>',
										page : '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
										next : '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
										onPageChange : function(num, type) {
											// alert("pageIndex="+num);
											// alert("type="+type);
											$("#pageIndex").val(num);
											
											var queryUrl = "queryByPage.do";
											$
													.ajax({
														url : queryUrl,
														dataType : 'json',
														data : {
															pageIndex : num,
															pageSize : pSize,
															id: proId 
														},
														cache : false,
														success : function(data) {

															$("#products tr:not(:first)").remove();
															var results = data.pageResult.resultList;
															for (i = 0; i < results.length; i++) {
																var detail = results[i];

																var rowContent = "<tr>"
																		+ "<td><input name='deId' class='checkbox' type='checkbox' value='"
																		+ detail.id
																		+ "'/></td>"
																		+ "<td>"
																		+ detail.proCode
																		+ "</td>"
																		+ "<td>"
																		+ detail.proName
																		+ "</td>"
																		+ "<td>"
																		+ detail.ruleCode
																		+ "</td>"
																		+ "<td>"
																		+ detail.ruleName
																		+ "</td>"
																		+ "<td>"
																		+"长:"+detail.longness+" 宽:"+detail.width+" 高:"+detail.height
																		+ "</td>"							
																		+ "<td>"
																		+ detail.color
																		+ "</td>"
																		+ "<td>"
																		+ detail.total
																		+ "</td>"
																		+ "<td>"
																		+ detail.enterPrice
																		+ "</td>"
																		+ "<td>"
																		+ detail.salePrice
																		+ "</td>"
																rowContent = rowContent
																		+ "<td><button name='editBtn' objId='"
																		+ detail.id+ "' class='btn btn-sm-block'>修改</button></td>"
																		+"</tr>";
																$("#products").append(rowContent);
															}

														},
														error : function(html) {
															return;
														}
													});
										}
									});

					/**
					 * 全选当前页记录
					 */
					$("#products").delegate('#selectAll', 'click', function() {
						var isSelectAll = $(this).prop('checked');
						$("input[name='deId']").each(function() {
							$(this).prop("checked", isSelectAll);
						});
					});
					
					
					
					$("#ruleName").delegate($(this), 'change', function() {
					        var  proName=$(this).val();
					        var queryUrl="queryProCodeByName.do";
					        $.ajax({
								url : queryUrl,
								dataType : 'text',
								data : {
									
									proName: proName 
								},
								cache : false,
								success : function(data) {
									alert("------------"+data)
									$("#ruleCode").val(data);

								},
								error : function(html) {
									alert("获取类型编号失败");
									
								}
							});
					});

					/**
					 * 修改按钮事件
					 */

					$("#products").delegate('[name="editBtn"]', 'click',
							function() {
						
								var proId = $(this).attr("objId");
                               
								var editUrl = "show.do";
								$.ajax({

									url : editUrl,
									dataType : 'json',
									data : {
										id : proId
									},
									cache : false,

									success : function(data) {

										loadDetail(data);
									},
									error : function(html) {
										
										alert("Load Data failly");
										refresh();
									}
								});

							});

					
					$("#tools").delegate('#deleteBtn', 'click', function() {
						delChk = $('input[name="deId"]:checked');

						if (delChk.length > 0) {
							if (confirm("Are you sure delete the record?")) {

								var ids = "";
								/* var delUrl = "delete.do?ids="; */
								var delUrl = "delete.do";
								var idArr = new Array();

								for (var i = 0; i < delChk.length; i++) {
									idArr.push(delChk.get(i).value);

								}

								$.ajax({
									url : delUrl,
									type : "POST",
									data : {
										ids : idArr.toString()
									},
									cache : false,

									success : function(html) {
										alert("Delete successfully");
										refresh();
									},
									error : function(html) {
										alert("Delete failly");
										refresh();
									}
								});
							} else {
								return;
							}
						} else {
							alert("Please select the record to delete");
							return;
						}
					});

					$("#tools").delegate('#addProduct', 'click', function() {

						
						
						var proId = $("#productId").val();
						
						var editUrl = "add.do";
						$.ajax({

							url : editUrl,
							dataType : 'json',
							data : {
								id : proId
							},
							cache : false,

							success : function(data) {

								
								$("#detailDialog input").each(function() {
									$(this).prop("value", null);
									$(this).prop("readonly", false);

								});
								$("#detailDialog textarea").each(function() {
									$(this).prop("value", null);

								});
								
								$("#proCode").prop("readonly", true);
								$("#proName").prop("readonly", true);
								
								loadDetail(data);
								
							},
							error : function(html) {
								
								alert("Load Data failly");
								refresh();
							}
						});
						
					
					});

					function loadResource() {

						alert("resource..");
					}

					function loadDetail(detail) {

						$("#proId").val(detail.id);
						$("#proCode").val(detail.proCode);
						$("#proName").val(detail.proName);
						$("#ruleCode").val(detail.ruleCode);
						$("#ruleName").val(detail.ruleName);
						$("#minTotal").val(detail.minTotal);
						
						$("#width").val(detail.width);
						$("#height").val(detail.height);
						$("#longness").val(detail.longness);
						$("#total").val(detail.total);
						$("#useful").val(detail.useful);
						$("#color").val(detail.color);
						$("#enterPrice").val(detail.enterPrice);
						$("#salePrice").val(detail.salePrice);
						$("#description").val(detail.description);
						$("#detailDialog").modal("show");
					}

					function vaildate(form) {
						return true;
					}

					function refresh() {
						window.location.reload();
					}
					
					function initUploader() {
						uploader = new plupload.Uploader(
								{
									runtimes : 'html5,flash,silverlight,html4',
									browse_button : 'picSelect', // you can
									// pass in
									// id...
									container : document
											.getElementById('pic'), // ...
									// or
									// DOM
									// Element
									// itself
									url : 'uploadMainImg.do',
									flash_swf_url : '<%=request.getContextPath()%>/manage/js/plupload/Moxie.swf',
									silverlight_xap_url : '<%=request.getContextPath()%>/manage/js/plupload/Moxie.xap',
									resize: {width: 120, height: 320, quality: 90},
									filters : {
										max_file_size : '10mb',
										mime_types : [ {
											title : "Image files",
											extensions : "jpg,gif,png"
										},
										
										]
									},

									init : {
										PostInit : function() {
											document.getElementById('pic').value = '';

										},

										FilesAdded : function(up, files) {
											plupload
													.each(
															files,
															function(file) {
																document
																		.getElementById('pic').value = "";
																document
																		.getElementById('pic').value = file.name;
																
																document
																.getElementById('pic').blur();
																
													
															});
										},

										UploadProgress : function(up, file) {

										},
										FileUploaded : function(up, file,result) {
											
											alert("文件上传成功" + result.response);
											
											$("#mainImg").attr("src",
													result.response);
											$("#pic").val(result.response);
											$("#pic").blur();
										},

										Error : function(up, err) {
											// document.getElementById('console').innerHTML
											// += "\nError #" + err.code + ": "
											// + err.message;
											alert("上传文件失败");
										}

									}
								});
						
						
						$('#uploadBtn').delegate($(this),'click',function() {
							if(uploader!=null && uploader!="undefined"){
								uploader.start();
								return false;
							}
					
						});
						uploader.init();
					}
				});
